/**
 * user
 * @author MrZhong [ 799149346@qq.com / http://github.com/Mr-ZhongWeiWei ]
 * @date 2021/12/15
 */

import {createSlice, createAsyncThunk} from "@reduxjs/toolkit"
import {ACCESS_TOKEN} from "../mutation-types";
import {login, logout, getInfo} from "@/api/user"
import storage from 'store'

export const Login = createAsyncThunk('user/Login', async (param) => {
    const result =  login(param)
    return result
})

export const Logout = createAsyncThunk('user/Logout',async (param) => {
    const {result} = await logout(param).then(() => {
        storage.remove(ACCESS_TOKEN)
        window.location.href = '/user/login'
    })
    return result
})

export const GetInfo = createAsyncThunk('user/GetInfo', async (param) => {
    const result = await getInfo(param)
    return result
})

export const user = createSlice({
    name: 'user',
    initialState: {
        token: '',
        roles: [],
        info: {}
    },
    reducers: {
        setToken: (state, {payload}) => {
            if (!payload) {
                payload = ''
            } else {
                storage.set(ACCESS_TOKEN, payload)
            }
            state.token = payload
        }
    },
    extraReducers: {
        [Login.fulfilled]: (state, {payload}) => {
            const token = payload.data
            state.token = token
            storage.set(ACCESS_TOKEN, token, 7 * 24 * 60 * 60 * 1000)
        },
        [Logout.fulfilled]: (state) => {
            state.token = ''
        },
        [GetInfo.fulfilled]: (state, { payload }) => {
            state.roles =   payload.data.role
            state.info  =   payload.data
        },
        [GetInfo.rejected]: (state, data) => {
            console.log(data)
        }
    }
})

export const {setToken} = user.actions

export default user.reducer
